﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace TextMixer
{
    public partial class MainWindow : Window
    {
        private Random random = new Random((int)DateTime.Now.Ticks);

        public MainWindow()
        {
            InitializeComponent();
        }

        public string Mix(string s)
        {
            char[] text = s.ToCharArray();
            int len = text.Length;
            int i = 0;

            while (i <  len)
            {
                while (i < len && IsSeparator(text[i]))
                {
                    ++i;
                }
                
                int start = i;

                while (i < len && !IsSeparator(text[i]))
                {
                    ++i;
                }

                Shuffle(ref text, start + 1, i - 1);
            }

            return new string(text);
        }

        public void Shuffle(ref char[] text, int start, int end)
        {
            if (start == end)
            {
                return;
            }

            for (int i = start; i < end; ++i)
            {
                int j = random.Next(i, end);
                Swap(ref text[i], ref text[j]);
            }
        }

        public void Swap(ref char a, ref char b)
        {
            char temp = a;
            a = b;
            b = temp;
        }

        private void txtOriginalText_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtMixedText.Text = Mix(txtOriginalText.Text);
        }

        private static bool IsSeparator(char c)
        {
            return !Char.IsLetter(c);
        }
    }
}
